<template>
  <div id="register">
    <h3>重置密码</h3>
    <van-form @submit="onSubmit">
      <van-field
        v-model="temp.userName"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="temp.email"
        name="邮箱"
        label="邮箱"
        placeholder="邮箱"
        :rules="[{ required: true, message: '请填写邮箱' }]"
      />
      <van-field
        v-model="temp.code"
        center
        clearable
        label="邮箱验证码"
        placeholder="请输入邮箱验证码"
      >
        <template #button>
          <van-button v-show="flag == true" size="small" type="primary" @click.prevent="subCode">发送验证码</van-button>
          <van-button v-show="flag !=true" size="small" type="primary" disabled >{{time}}秒后可重新发送</van-button>
        </template>
      </van-field>
      <van-field
        v-model="temp.password"
        type="password"
        name="新的密码"
        label="新的密码"
        placeholder="新的密码"
        :rules="[{ required: true, message: '新的密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { save,getResetCode, changePasswordByEmailCheck} from "@/api/user";
export default {
  data() {
    return {
      time: 0,
      flag: true,
      temp: {
        userName: undefined,
        password: undefined,
        email: undefined,
        code:undefined
      },
    };
  },
  methods: {
    onSubmit(values) {
      changePasswordByEmailCheck(this.temp).then((Response) => {
        if (Response.code === "200") {
          this.$notify({
            message: "密码重置成功！！请重新登录！！",
            type: "success",
          });
          this.$router.push("/login");
        }
      });
    },
    subCode() { // 获取验证码
        if (this.temp.email && this.temp.userName) {
            this.flag = false
            this.time = 60
            let interval = setInterval(()=>{
                this.time--
                if (this.time < 0) {
                    this.flag = true
                    clearInterval(interval)
                }
            },1000)
            getResetCode(this.temp.userName,this.temp.email).then(response => {
            if (response.code === '200') {
                this.$notify({
                    message:'发送成功！！',
                    type:'success'
                })
            }
        })
        } else {
            this.$notify({
                message:'请填写邮箱和用户名！！',
                type:'warning'
            })
        }
    },
  },
};
</script>

<style>
#register h3 {
  color: orange;
  font-size: 40px;
  text-align: center;
}
</style>